package codeformat;

import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.components.PersistentStateComponent;
import com.intellij.openapi.components.State;
import com.intellij.openapi.components.Storage;
import org.jdom.Element;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;

import java.time.LocalTime;
import java.time.format.DateTimeFormatter;

@State(
        name = "OffDutyTimeConfig",
        storages = @Storage("off-duty-timer.xml")
)
public class OffDutyTimeConfig implements PersistentStateComponent<Element> {
    private LocalTime offDutyTime = LocalTime.of(18, 0); // 默认下班时间为18:00
    private static final DateTimeFormatter TIME_FORMATTER = DateTimeFormatter.ofPattern("HH:mm");

    public static OffDutyTimeConfig getInstance() {
        return ApplicationManager.getApplication().getService(OffDutyTimeConfig.class);
    }

    @Nullable
    @Override
    public Element getState() {
        Element element = new Element("OffDutyTimeConfig");
        element.setAttribute("offDutyTime", offDutyTime.format(TIME_FORMATTER));
        return element;
    }

    @Override
    public void loadState(@NotNull Element state) {
        String timeStr = state.getAttributeValue("offDutyTime");
        if (timeStr != null) {
            try {
                offDutyTime = LocalTime.parse(timeStr, TIME_FORMATTER);
            } catch (Exception e) {
                offDutyTime = LocalTime.of(18, 0); // 解析失败则使用默认时间
            }
        }
    }

    public LocalTime getOffDutyTime() {
        return offDutyTime;
    }

    public void setOffDutyTime(LocalTime offDutyTime) {
        this.offDutyTime = offDutyTime;
    }
}